package com.kun.controller;

import com.kun.entity.Dept;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private RestTemplate restTemplate;

//    private static final String REST_URL_PREFIX = "http://localhost:8001";
    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";


    @GetMapping("/queryById/{id}")
    @CircuitBreaker(name = "SPRINGCLOUD-PROVIDER-DEPT", fallbackMethod = "queryByIdFallback_circuitBreaker")
    @Bulkhead(name = "SPRINGCLOUD-PROVIDER-DEPT", type = Bulkhead.Type.THREADPOOL,fallbackMethod = "queryByIdFallback_bulkhead" )
    public Object queryById(@PathVariable("id") Long id) {
        Dept dept = restTemplate.getForObject(REST_URL_PREFIX + "/dept/" + id, Dept.class);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (dept == null) {
            throw new RuntimeException("Dept not found");
        }
        return dept;
    }


    public ResponseEntity queryByIdFallback_bulkhead(Long id, Throwable e) {
        Dept dept = new Dept();
        dept.setDeptNo(id);
        dept.setDName("Fallback: 由于高并发，该服务不可用");
        return new ResponseEntity(dept, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public ResponseEntity queryByIdFallback_circuitBreaker(Long id, Throwable e) {
        Dept dept = new Dept();
        dept.setDeptNo(id);
        dept.setDName("no this dept");
        return new ResponseEntity(dept, HttpStatus.INTERNAL_SERVER_ERROR);
    }










}
